const express = require("express");
const app = express();
app.use(express.static("www"));

const http = require("http");
//创建一个server 服务器
const server = http.createServer(app);
// 引入WebSocket 模块
const WebSocket = require("ws");
const webSocketServer = new WebSocket.Server({ server })

var userList = [];

webSocketServer.on("connection", function (ws, req) {
    // console.log("ws",ws);
    // console.log("req",req);
    // console.log(req.url);
    ws.username = req.url.substring(1);

    ws.username = decodeURI(ws.username)
    // ws.username = user;


    userList.forEach((item) => {
        var obj = {
            data: `${ws.username}进来了`
        }
        item.send(JSON.stringify(obj));
    })

    userList.push(ws);
    var obj = {
        data: `${ws.username}欢迎来到聊天群`
    }
    ws.send(JSON.stringify(obj));

    ws.on("message", function (req) {
        var res = JSON.parse(req);
        userList.forEach((item) => {
            var obj = {
                data: res.data, 
                user: ws.username
            }
            item.send(JSON.stringify(obj));
        })
    })
    ws.on("close", function () {
        var i = userList.indexOf()
    })
})
server.listen(3000, () => {
    console.log("localhost:3000");
})